package com.flyco.roundview;

import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.utils.Rect;
import ohos.app.Context;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;

import java.io.IOException;

public class RoundLinearLayout extends DirectionalLayout implements Component.LayoutRefreshedListener {

    private RoundViewDelegate delegate;

    public RoundLinearLayout(Context context) {
        this(context, null);
    }

    public RoundLinearLayout(Context context, AttrSet attrs) {
        super(context, attrs);
        if(attrs==null)
        {
            return;
        }
        delegate = new RoundViewDelegate(this, context, attrs);
        setLayoutRefreshedListener(this::onRefreshed);
    }


    /**
     * Gets delegate.
     *
     * @return the delegate
     */
    public RoundViewDelegate getDelegate() {
        return delegate;
    }

    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (delegate.isWidthHeightEqual() && getWidth() > 0 && getHeight() > 0) {
            int max = Math.max(getWidth(), getHeight());
            int measureSpec = MeasureSpec.getMeasureSpec(max, MeasureSpec.PRECISE);
            setComponentSize(measureSpec, measureSpec);
            return;
        }
        setComponentSize(widthMeasureSpec, heightMeasureSpec);
    }

    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        if (delegate.isRadiusHalfHeight()) {
            delegate.setCornerRadius(getHeight() / 2);
        } else {
            delegate.setBgSelector();
        }
    }

    @Override
    public void onRefreshed(Component component) {
        int widthSpec = new UiUtil(getContext()).getMeasureSpec(ComponentContainer.LayoutConfig.MATCH_PARENT,
            getWidth());
        int heightSpec = new UiUtil(getContext()).getMeasureSpec(ComponentContainer.LayoutConfig.MATCH_PARENT,
            getHeight());
        onMeasure(widthSpec, heightSpec);
        Rect parentRect = getComponentPosition();
        onLayout(true, parentRect.left, parentRect.top, parentRect.right, parentRect.bottom);
    }
}
